package cn.iocoder.yudao.module.jky.service.goodscat;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.jky.controller.admin.goodscat.vo.*;
import cn.iocoder.yudao.module.jky.convert.goodscat.GoodsCatConvert;
import cn.iocoder.yudao.module.jky.dal.dataobject.goodscat.GoodsCatDO;
import cn.iocoder.yudao.module.jky.dal.dataobject.goodscatdept.GoodsCatDeptDO;
import cn.iocoder.yudao.module.jky.dal.mysql.goodscat.GoodsCatMapper;
import cn.iocoder.yudao.module.jky.dal.mysql.goodscatdept.GoodsCatDeptMapper;
import cn.iocoder.yudao.module.jky.service.goodscatdept.GoodsCatDeptService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.jky.enums.ErrorCodeConstants.GOODS_CAT_NOT_EXISTS;

/**
 * 商品分类 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
@DS("slave")
public class GoodsCatServiceImpl implements GoodsCatService {

    @Resource
    private GoodsCatMapper goodsCatMapper;

    @Resource
    private GoodsCatDeptMapper goodsCatDeptMapper;

    @Resource
    private GoodsCatDeptService goodsCatDeptService;

    @Resource
    private AdminUserApi adminUserApi;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public Short createGoodsCat(GoodsCatCreateReqVO createReqVO) {
        // 插入
        GoodsCatDO goodsCat = GoodsCatConvert.INSTANCE.convert(createReqVO);
        // 全部是自营商城
        goodsCat.setType(1);
        goodsCat.setCreateTime(LocalDateTime.now());
        goodsCat.setIsShow("N");
        goodsCatMapper.insert(goodsCat);

        // 如果不是供应商新增商品分类，则要在表单中选好部门再新增
        goodsCatDeptService.createGoodsCatDept(goodsCat.getCatId(),createReqVO.getDeptId());
        // 返回
        return goodsCat.getCatId();
    }

    @Override
    public void updateGoodsCat(GoodsCatUpdateReqVO updateReqVO) {
        // 校验存在
        validateGoodsCatExists(updateReqVO.getCatId());
        // 更新
        GoodsCatDO updateObj = GoodsCatConvert.INSTANCE.convert(updateReqVO);
        goodsCatMapper.updateById(updateObj);
    }

    @Override
    public void updateGoodsCatState(GoodsCatUpdateStateReqVO updateStateReqVO) {
        // 校验存在
        validateGoodsCatExists(updateStateReqVO.getCatId());
        // 更新
        GoodsCatDO updateObj = GoodsCatConvert.INSTANCE.convert(updateStateReqVO);
        goodsCatMapper.updateById(updateObj);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void deleteGoodsCat(Short id) {
        // 校验存在
        validateGoodsCatExists(id);
        // 删除
        goodsCatMapper.deleteById(id);
        // 删除关联表
        goodsCatDeptService.deleteByCatId(id);
    }

    private void validateGoodsCatExists(Short id) {
        if (goodsCatMapper.selectById(id) == null) {
            throw exception(GOODS_CAT_NOT_EXISTS);
        }
    }

    @Override
    public GoodsCatDO getGoodsCat(Short id) {
        return goodsCatMapper.selectById(id);
    }

    @Override
    public List<GoodsCatDO> getGoodsCatList(Collection<Short> ids) {
        return goodsCatMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<GoodsCatDO> getGoodsCatPage(GoodsCatPageReqVO pageReqVO) {

        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        assert loginUser != null;

        // 如果是供应商管理员,获取供应商租户的所有部门，拿到当前租户下的所有分类
        if (loginUser.getId() == 110) {

            List<GoodsCatDeptDO> goodsCatDeptDOS = goodsCatDeptService.getGoodsCatDeptList();

            if (CollectionUtil.isNotEmpty(goodsCatDeptDOS)) {
                List<Short> catIds = goodsCatDeptDOS.stream().map(GoodsCatDeptDO::getCatId).collect(Collectors.toList());
                pageReqVO.setCatIdList(catIds);
                return supplierNameHandle(goodsCatMapper.selectPage(pageReqVO));
            }
            return new PageResult<GoodsCatDO>();
        }

        // 供应商用户可以直接查询本部门下的分类
        CommonResult<AdminUserRespDTO> user = adminUserApi.getUser(loginUser.getId());
        if (Objects.nonNull(user.getData().getDeptId())) {
            List<GoodsCatDeptDO> goodsCatDeptDOS = goodsCatDeptService.getGoodsCatDeptListByUser(user);
            if (CollectionUtil.isNotEmpty(goodsCatDeptDOS)) {
                List<Short> catIds = goodsCatDeptDOS.stream().map(GoodsCatDeptDO::getCatId).collect(Collectors.toList());
                pageReqVO.setCatIdList(catIds);
                return supplierNameHandle(goodsCatMapper.selectPage(pageReqVO));
            }
        }
        return new PageResult<GoodsCatDO>();
    }

    private PageResult<GoodsCatDO> supplierNameHandle(PageResult<GoodsCatDO> goodsCatDOPageResult) {
        goodsCatDOPageResult.getList().forEach(item -> {
            item.setSupplierName(goodsCatDeptService.getDeptNameByCatId(item.getCatId()));
        });
        return goodsCatDOPageResult;
    }


    @Override
    public List<GoodsCatDO> getGoodsCatList(GoodsCatExportReqVO exportReqVO) {
        return goodsCatMapper.selectList(exportReqVO);
    }

    @Override
    public List<GoodsCatDO> getGoodsCatList(GoodsCatListReqVO reqVO) {/*

        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        assert loginUser != null;

        // 如果是供应商管理员,获取供应商租户的所有部门，拿到部门下所有用户
        if (loginUser.getId() == 110) {
            List<GoodsCatDeptDO> goodsCatDeptDOS = goodsCatDeptMapper.selectList();
            List<Short> catIds = goodsCatDeptDOS.stream().map(GoodsCatDeptDO::getCatId).collect(Collectors.toList());
            return goodsCatMapper.selectList(new LambdaQueryWrapperX<GoodsCatDO>().in(GoodsCatDO::getCatId,catIds));
        }

        // 供应商用户可以直接查询本部门下的分类
        CommonResult<AdminUserRespDTO> user = adminUserApi.getUser(loginUser.getId());
        List<GoodsCatDeptDO> goodsCatDeptDOS = goodsCatDeptMapper.selectList(new LambdaQueryWrapperX<GoodsCatDeptDO>()
                .eq(GoodsCatDeptDO::getCatId, user.getData().getDeptId()));
        List<Short> catIds = goodsCatDeptDOS.stream().map(GoodsCatDeptDO::getCatId).collect(Collectors.toList());
        return goodsCatMapper.selectList(new LambdaQueryWrapperX<GoodsCatDO>().in(GoodsCatDO::getCatId,catIds));


    */
        return goodsCatMapper.selectList();
    }

}
